package com.hyjiacan.h2c.commands

import com.hyjiacan.h2c.Cmd

object CommandManager {
    private val commands: MutableMap<String, ICommand> = mutableMapOf()

    private fun register(command: ICommand) {
        commands[command.name] = command
    }

    init {
        register(CommandExit())
//        register(CommandShowTables())
        register(CommandRunFile())
        register(CommandExportTable())
        register(CommandStatement())
    }

    fun match(string: String): ICommand? {
        if (string == "h") {
            Cmd.printLine()
            printHelp()
            return null
        }
        commands.forEach { (t, u) ->
            if (u.test(string)) {
                return u
            }
        }
        Cmd.pl("无法识别的命令: $string")
        Cmd.printLine()
        printHelp()
        return null
    }

    private fun printHelp() {
        Cmd.pl("命令 - 帮助", false)
        Cmd.pl("--------", false)
        val items = mutableListOf<String>()
        val longestName = commands.keys.maxOf {
            return@maxOf it.length
        }
        commands.forEach { (t, u) ->
            items.add("${t.padEnd(longestName + 4, ' ')}${u.description}")
        }
        Cmd.pl(items.joinToString("\n"), false)
    }
}